package com.fengjue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengjue.common.RespBean;
import com.fengjue.pojo.MenuRole;
import com.fengjue.mapper.MenuRoleMapper;
import com.fengjue.service.IMenuRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengjue
 * @since 2021-03-10
 */
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements IMenuRoleService {

    @Autowired
    private MenuRoleMapper menuRoleMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    @Transactional
    public RespBean updateMenuRole(Integer rid, Integer[] mids) {

        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        MenuRoleMapper mapper = session.getMapper(MenuRoleMapper.class);

        menuRoleMapper.delete(new QueryWrapper<MenuRole>()
        .eq("rid",rid)
        );

        if(null ==mids&& mids.length==0){
            return  RespBean.success("更新成功");

        }

        MenuRole menuRole = new MenuRole();
        menuRole.setRid(rid);
        int insert = 0;
        for (int mid : mids) {

            menuRole.setMid(mid);
            mapper.insert(menuRole);
            insert++;
        }
        session.commit();
        session.clearCache();

        if(insert==mids.length){
            return  RespBean.success("更新成功");

        }
        return  RespBean.error("更新失败");

    }
}
